﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using Castle.Core.Resource;
using MailKit.Search;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    ///  组件报价申请运算
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CRMPriceReportController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_zh;
        public readonly string con_qh;
        public readonly string con_yb;
        public readonly string con_oa;


        public CRMPriceReportController(ILogger<CRMPriceReportRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_zh = _configuration.GetConnectionString("WMSDbConnection_ZH");
            con_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_yb = _configuration.GetConnectionString("WMSDbConnection_YB");
            con_oa = _configuration.GetConnectionString("OA_DbConnection");
            _logger = loggerFactory.CreateLogger<CRMPriceReportController>();
        }

        /// <summary>
        /// 组件报价申请运算
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostAddCRMPriceReport([FromBody] CRMPriceReportRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            CRMPriceReportResponseDto re = new CRMPriceReportResponseDto();

            try
            {
                dic = new Dictionary<string, string>();
                dic.Add("source_no", "");
                //DataTable ma_dt = MethodHelp.GetTableInfo("TMS0131", dic, con);
                DataTable ma_dt = MethodHelp.GetTableInfo("TMS0155", dic, con);//获取待运算数据
                if (ma_dt.Rows.Count > 0)
                {
                    foreach (DataRow item in ma_dt.Rows)
                    {
                        dic = new Dictionary<string, string>();
                        dic.Add("requestid", item["requestid"].ToString());
                        string strSql_oa= MethodHelp.GetTranSQL("TMS0156", dic, con);//获取OA报价单号-打印申请后的数据
                        if (strSql_oa !="")
                        {
                            DataTable dt_oa = DB.MSSQuery(strSql_oa, con_oa);
                            if (dt_oa.Rows.Count>0)
                            {
                                dic = new Dictionary<string, string>();
                                dic.Add("djh", item["djh"].ToString());
                                string strSql2 = MethodHelp.GetTranSQL("TMS0137", dic, con);//更新报价单运算记录标记
                                if (strSql2 != "")
                                {
                                    strSqlList.Add(strSql2);

                                    dic = new Dictionary<string, string>();
                                    //dic.Add("djbh", item["OA报价单号"].ToString());
                                    dic.Add("djbh", dt_oa.Rows[0]["djbh"].ToString());
                                    string sqlstr = MethodHelp.GetTranSQL("TMS0135", dic, con);//查询组件报价申请运算_单据数据源_报价明细_OA
                                    if (sqlstr != "")
                                    {
                                        DataTable dt_bmx = DB.MSSQuery(sqlstr, con_oa);
                                        if (dt_bmx.Rows.Count > 0)
                                        {
                                            foreach (DataRow row in dt_bmx.Rows)
                                            {
                                                dic = new Dictionary<string, string>();
                                                dic.Add("djbh", row["报价单号"].ToString());
                                                dic.Add("zjcp", row["产品型号"].ToString());
                                                dic.Add("zlgl", row["主流功率"].ToString());
                                                string sqlstr2 = MethodHelp.GetTranSQL("TMS0136", dic, con);
                                                if (sqlstr2 != "")
                                                {
                                                    DataTable dt_cb = DB.MSSQuery(sqlstr2, con_oa);
                                                    if (dt_cb.Rows.Count > 0)
                                                    {
                                                        dic = new Dictionary<string, string>();
                                                        dic.Add("price_no", item["djh"].ToString());
                                                        dic.Add("oa_priceno", dt_oa.Rows[0]["djbh"].ToString());
                                                        dic.Add("order_title", item["标题"].ToString());
                                                        dic.Add("applicant_user", item["申请人"].ToString());
                                                        dic.Add("applicant_depart", item["申请部门"].ToString());
                                                        dic.Add("applicant_date", DB.ToDateTime(item["申请日期"].ToString()).ToShortDateString());
                                                        dic.Add("customer_name", item["客户名称"].ToString());
                                                        dic.Add("project_name", item["项目名称"].ToString());
                                                        dic.Add("report_type", item["报价单类型"].ToString());
                                                        dic.Add("payment_type", item["收款条件"].ToString());
                                                        dic.Add("trading_type", item["交易方式"].ToString());
                                                        dic.Add("project_location", item["项目地点"].ToString());
                                                        dic.Add("order_qty", DB.ToDouble(row["数量(MW)"].ToString()).ToString());
                                                        dic.Add("delivery_begintime", DB.ToDateTime(item["预计交期开始时间"].ToString()).ToShortDateString());
                                                        dic.Add("delivery_endtime", DB.ToDateTime(item["预计交期结束时间"].ToString()).ToShortDateString());
                                                        dic.Add("is_gokin", item["产品是否高景标准"].ToString());
                                                        dic.Add("is_stock", item["是否可发库存"].ToString());
                                                        dic.Add("is_adjustprice", item["是否有调价机制"].ToString());
                                                        dic.Add("price_remarks", item["备注信息（非标需求等成本增加项）"].ToString());
                                                        dic.Add("oa_state", item["OA流程状态"].ToString());
                                                        dic.Add("product_model", row["产品型号"].ToString());
                                                        dic.Add("product_power", row["主流功率"].ToString());
                                                        dic.Add("first_price", DB.ToDouble(row["首次报价（元/W)"].ToString()).ToString());
                                                        dic.Add("modify_price", DB.ToDouble(row["修改报价"].ToString()).ToString());
                                                        dic.Add("final_price", DB.ToDouble(row["最终报价（元/瓦)"].ToString()).ToString());
                                                        dic.Add("single_midprice", DB.ToDouble(row["单W居间费"].ToString()).ToString());
                                                        dic.Add("single_shipprice", DB.ToDouble(row["单W运费"].ToString()).ToString());
                                                        dic.Add("restore_price", DB.ToDouble(row["还原出厂价"].ToString()).ToString());
                                                        dic.Add("guidance_price", DB.ToDouble(row["指导价（出厂价）"].ToString()).ToString());
                                                        dic.Add("capital_cost", DB.ToDouble(dt_cb.Rows[0]["资金成本"].ToString()).ToString());
                                                        dic.Add("gift_price", DB.ToDouble(dt_cb.Rows[0]["赠品及备品备件"].ToString()).ToString());
                                                        dic.Add("premium_price", DB.ToDouble(dt_cb.Rows[0]["保险费"].ToString()).ToString());
                                                        dic.Add("other_price", DB.ToDouble(dt_cb.Rows[0]["其他"].ToString()).ToString());
                                                        dic.Add("hit_rate", dt_cb.Rows[0]["订单命中率（%）"].ToString());
                                                        dic.Add("battery_price", DB.ToDouble(dt_cb.Rows[0]["电池成本（元/W）"].ToString()).ToString());
                                                        dic.Add("nosilicon_price", DB.ToDouble(dt_cb.Rows[0]["非硅材料（元/W）"].ToString()).ToString());
                                                        dic.Add("manufacturing_cost", DB.ToDouble(dt_cb.Rows[0]["制造成本（元/W）"].ToString()).ToString());
                                                        dic.Add("loss_price", DB.ToDouble(dt_cb.Rows[0]["制程损失（元/W）"].ToString()).ToString());
                                                        dic.Add("production_costs", DB.ToDouble(dt_cb.Rows[0]["制造成本合计"].ToString()).ToString());
                                                        dic.Add("single_gprice", DB.ToDouble(dt_cb.Rows[0]["单W毛利"].ToString()).ToString());
                                                        string strSQL = MethodHelp.GetTranSQL("TMS0132", dic, con);
                                                        if (strSQL != "")
                                                        {
                                                            strSqlList.Add(strSQL.ToString());
                                                        }
                                                        else
                                                        {
                                                            strMsg = "Parameter conversion failed";
                                                        }
                                                    }
                                                }

                                            }
                                        }
                                    }

                                }
                            }
                        }                                       
                    }

                    if (strSqlList.Count > 0)
                    {
                        bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                        if (A)
                        {

                        }
                        else
                        {
                            strMsg = "Database update failed";
                        }

                    }
                    else
                    {
                        strMsg = "No insertion data present";
                    }
                }


            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            //_logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
